package com.sgb.kjwl.view.ui.activity.transport;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.fondesa.recyclerviewdivider.DividerDecoration;
import com.google.gson.JsonObject;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.api.UrlConfig;
import com.sgb.kjwl.databinding.ActivityPayGeneralQuotationBinding;
import com.sgb.kjwl.model.entity.CarInfo;
import com.sgb.kjwl.model.entity.GoodsOrderEntity;
import com.sgb.kjwl.model.entity.OrderEntity;
import com.sgb.kjwl.model.entity.self.GoodsSourceDetail;
import com.sgb.kjwl.model.entity.transport.CargoPublishEntity;
import com.sgb.kjwl.model.entity.transport.SingleItemEntity;
import com.sgb.kjwl.utils.CargoConstant;
import com.sgb.kjwl.utils.DefaultUtil;
import com.sgb.kjwl.utils.NumberUtil;
import com.sgb.kjwl.view.constant.RouterKey;
import com.sgb.kjwl.view.event.LogisticsEvent;
import com.swgk.core.event.MenuEvent;
import com.sgb.kjwl.view.event.WebEvent;
import com.sgb.kjwl.view.ui.activity.WebActivity;
import com.sgb.kjwl.view.ui.activity.self.AddCarInfoActivity;
import com.sgb.kjwl.view.ui.adapter.transport.CargoCustomValueAdapter;
import com.sgb.kjwl.view.ui.adapter.transport.PayGoodsInfoAdapter;
import com.sgb.kjwl.view.widget.CarListPopWindow;
import com.sgb.kjwl.view.widget.WrapLinearLayout;
import com.sgb.kjwl.view.widget.transport.AMapDialog;
import com.sgb.kjwl.viewmodel.transport.PayGeneralQuotationViewModel;
import com.sgb.link.entity.AMapAddressEntity;
import com.sgb.link.utils.RoundDialogHelper;
import com.swgk.core.customview.ItemInputTextView;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.dialog.RoundDialog;
import com.swgk.core.event.EventConstant;
import com.swgk.core.util.DateUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author: 熊丽
 * @date: 2021/9/22
 * @Description: 普通货源-新报价
 */
public class PayGeneralQuotationOrderActivity extends AppActivity implements ItemInputTextView.OnWholeItemClickListener {
    public static final int REQUEST_CODE = 200;
    public static final int RESULT_CODE = 201;
    ActivityPayGeneralQuotationBinding mBinding;
    PayGeneralQuotationViewModel mViewModel;
    //车辆选择
    private final List<CarInfo> mCarList = new ArrayList<>();
    private OptionsPickerView<CarInfo> mCarPicker;
    //货源no
    private String mSourceNo;
    //货源信息
    private List<SingleItemEntity> mGoodsList;

    //货车信息
    private List<SingleItemEntity> mCarInfoList;
    private PayGoodsInfoAdapter mCarInfoAdapter;
    //自定义字段列表
    private List<SingleItemEntity> mCustomList;
    private CargoCustomValueAdapter mCustomAdapter;
    GoodsSourceDetail goodsSourceDetail;
    GoodsOrderEntity mEntity = new GoodsOrderEntity();
    private static final int TO_GOODS_ORDER = 100;//跳转订单详情
    String orderNo;
    private CarInfo car;
    private int pos;
    private String carOfferNo;
    private OrderEntity mOrderEntity;
    CarListPopWindow carListPopWindow;
    private String offerNo;
    private boolean isManager;
    private Calendar selectedDate = Calendar.getInstance();
    Drawable drawableSelect = null;
    Drawable drawableUnSelect = null;

    public static void start(Context context, String no, GoodsSourceDetail goodsSourceDetail) {
        Intent intent = new Intent(context, PayGeneralQuotationOrderActivity.class);
        intent.putExtra(RouterKey.NO, no);
        intent.putExtra(RouterKey.DATA, goodsSourceDetail);
        context.startActivity(intent);
    }

    public static void start(Context context, String no) {
        Intent intent = new Intent(context, PayGeneralQuotationOrderActivity.class);
        intent.putExtra(RouterKey.NO, no);
        context.startActivity(intent);
    }

    /**
     * 默认请求码为 200
     */
    public static void startForResult(Activity activity, String no, boolean isManager, boolean isDriver, String freight) {
        Intent intent = new Intent(activity, PayGeneralQuotationOrderActivity.class);
        intent.putExtra(RouterKey.NO, no);
        intent.putExtra(RouterKey.BOOLEAN, isManager);
        intent.putExtra(RouterKey.OWNER, isDriver);
        intent.putExtra(RouterKey.STRING, freight);
        activity.startActivityForResult(intent, REQUEST_CODE);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    protected void initView() {
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_pay_general_quotation);
        mViewModel = new ViewModelProvider(this).get(PayGeneralQuotationViewModel.class);
        mBinding.setLifecycleOwner(this);
        carOfferNo = getIntent().getStringExtra(RouterKey.CAROFFERNO);
        mBinding.includeTitle.titleView.setText("确认报价");
        mBinding.includeTitle.ivBack.setOnClickListener(v -> {
            finish();
        });
        mBinding.tvCargoOrdersProtocol.setText(Html.fromHtml("确认提交即表示您已阅读并同意"
                + "<font color='#5792FD'>《经营帮货物运输协议》</font>全部内容"));
        drawableSelect = getResources().getDrawable(R.drawable.icon_selected);
        drawableUnSelect = getResources().getDrawable(R.drawable.icon_unselecte);
        //设置drawable对象的大小
        drawableSelect.setBounds(0, 0, drawableSelect.getMinimumWidth(), drawableSelect.getMinimumHeight());
        //设置drawable对象的大小
        drawableUnSelect.setBounds(0, 0, drawableUnSelect.getMinimumWidth(), drawableUnSelect.getMinimumHeight());
        //设置CheckBox对象的位置，对应为左、上、右、下
        mBinding.btnAllFreight.setCompoundDrawables(drawableSelect, null, null, null);
        mBinding.btnFreight.setCompoundDrawables(drawableUnSelect, null, null, null);
        mBinding.btnAllFreight.setChecked(true);

        initRecycler();
        initEvent();
        initData();
    }

    private void initRecycler() {
        goodsSourceDetail = (GoodsSourceDetail) getIntent().getSerializableExtra(RouterKey.DATA);
        mSourceNo = getIntent().getStringExtra(RouterKey.NO);
        isManager = getIntent().getBooleanExtra(RouterKey.BOOLEAN, false);
        mEntity.setGoodsSourceNo(mSourceNo);
        mViewModel.getQuickBankList(this);
        //货源信息
        mGoodsList = new ArrayList<>();
        if (goodsSourceDetail != null) {
            mViewModel.syncGoodsInfo(mGoodsList, goodsSourceDetail);
            loadData(goodsSourceDetail);
        } else {
            mViewModel.getGoodsDetail(this, mSourceNo, mGoodsList);
        }
        //货车信息
        mCarInfoList = new ArrayList<>();

/*        mCarInfoAdapter = new PayGoodsInfoAdapter(mCarInfoList);
        mBinding.rvCargoOrdersCar.setNestedScrollingEnabled(false);
        mBinding.rvCargoOrdersCar.setLayoutManager(new LinearLayoutManager(this));
        mCarInfoAdapter.bindToRecyclerView(mBinding.rvCargoOrdersCar);*/
        //自定义字段列表
        mCustomList = new ArrayList<>();
        mCustomAdapter = new CargoCustomValueAdapter(mCustomList);
        mBinding.rvCargoOrdersField.setNestedScrollingEnabled(false);
        mBinding.rvCargoOrdersField.setLayoutManager(new LinearLayoutManager(this));
        DividerDecoration.builder(this)
                .colorRes(R.color.transparent)
                .size(10, TypedValue.COMPLEX_UNIT_DIP)
                .build()
                .addTo(mBinding.rvCargoOrdersField);
        mCustomAdapter.bindToRecyclerView(mBinding.rvCargoOrdersField);
    }

    private void initEvent() {
        mBinding.setOnClick(this);
        mBinding.itemArriveTime.setOnWholeItemClickListener(this);
        mBinding.itemLocation.setOnWholeItemClickListener(this);
        mBinding.itemCarriageCar.setOnWholeItemClickListener(this);

        //自定义字段删除监听
        mCustomAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if (view.getId() == R.id.iv_release_cargo_del) {
                mCustomList.remove(position);
                mCustomAdapter.notifyDataSetChanged();
                if (mCustomList.size() == 0) {
                    mBinding.rvCargoOrdersField.setVisibility(View.GONE);
                }
            }
        });
        carListPopWindow = new CarListPopWindow(this);
        carListPopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object key1, Object key2, Object key3) {
                int pos = (int) key1;
                carSelect(pos);
            }
        });
        //接口回调
        mViewModel.ldCar.observe(this, carInfos -> {
            syncCarList(carInfos, false);
        });
        mViewModel.ldCarinfo.observe(this, carInfos -> {
            syncCarList(carInfos, true);
        });
        mViewModel.ldLocation.observe(this, this::syncLocation);
        mViewModel.ldDriverInfo.observe(this, driverInfo -> {
            mEntity.setContrcts(driverInfo.getName());
            mEntity.setContrctsNumber(driverInfo.getTelphone());
            // mViewModel.syncCarInfo(mCarInfoList, driverInfo);
            //  mCarInfoAdapter.notifyDataSetChanged();
        });
        mViewModel.ldTradeNo.observe(this, no -> {
            CargoQuotationSuccessActivity.startForResult(this, isManager, no, 1);
            offerNo = no;

        });
        mViewModel.ldSoureDetail.observe(this, goodsSourceDetail -> {
            loadData(goodsSourceDetail);
        });
    }

    private void initData() {
        //获取信息
        mViewModel.getCarInfo(this);
        mViewModel.getCurrentLocation(this);
        mViewModel.getDriverInfo();
    }

    public void loadData(GoodsSourceDetail goodsSourceDetail) {
        this.goodsSourceDetail = goodsSourceDetail;
        mEntity.setMessagePrice(goodsSourceDetail.getMessagePrice());
        //货物信息
        List<String> strings = new ArrayList<>();
        if (!TextUtils.isEmpty(goodsSourceDetail.getGoodsTypesName())) {
            strings.add(goodsSourceDetail.getGoodsTypesName());
        }
        if (goodsSourceDetail.getFreightType() != null && goodsSourceDetail.getFreightType() == 0 && !TextUtils.isEmpty(goodsSourceDetail.getFreight())) {
            strings.add(NumberUtil.trim0(goodsSourceDetail.getFreight()) + goodsSourceDetail.getFreightUnitType());
        }
        if (!TextUtils.isEmpty(goodsSourceDetail.getWeight())) {
            strings.add(NumberUtil.trim0(goodsSourceDetail.getWeight()) + "吨");
            mBinding.tvReleaseCargoWeight.setVisibility(View.VISIBLE);
        } else {
            mBinding.tvReleaseCargoWeight.setVisibility(View.GONE);
        }
        if (!TextUtils.isEmpty(goodsSourceDetail.getVolume())) {
            strings.add(NumberUtil.trim0(goodsSourceDetail.getVolume()) + "方");
            mBinding.tvReleaseCargoVolume.setVisibility(View.VISIBLE);
        } else {
            mBinding.tvReleaseCargoVolume.setVisibility(View.GONE);
        }
        if (goodsSourceDetail.getFreightType() != null) {
            if (goodsSourceDetail.getFreightType() == 1) {
//                mBinding.tvCargoOrdersFreight.setText(String.format("运费核算：%s", "电议"));
                mBinding.llPhoneFreight.setVisibility(View.VISIBLE);
                mBinding.rlHint.setVisibility(View.VISIBLE);
            } else {
//                mBinding.tvCargoOrdersFreight.setText(String.format("运费核算：%s元", NumberUtil.trim0(goodsSourceDetail.getAllFreight())));
            }
        } else {
//            mBinding.tvCargoOrdersFreight.setText(String.format("运费核算：%s元", NumberUtil.trim0(goodsSourceDetail.getAllFreight())));
        }
        //货主
        mBinding.itemGoodsOwnerName.setContent(goodsSourceDetail.getCompanyName());
        //运输货物
        StringBuilder goodType = new StringBuilder();
        if (!TextUtils.isEmpty(goodsSourceDetail.getGoodsTypeName())) {
            goodType.append(goodsSourceDetail.getGoodsTypeName());
        }
        if (!TextUtils.isEmpty(goodsSourceDetail.getSecondGoodsTypeName())) {
            goodType.append(TextUtils.isEmpty(goodsSourceDetail.getGoodsTypeName()) ? goodsSourceDetail.getSecondGoodsTypeName() : "/" + goodsSourceDetail.getSecondGoodsTypeName());
        }
        if (TextUtils.isEmpty(goodsSourceDetail.getGoodsTypeName()) && TextUtils.isEmpty(goodsSourceDetail.getSecondGoodsTypeName())) {
            mBinding.itemGoodsTypeName.setContent("/");
        } else {
            mBinding.itemGoodsTypeName.setContent(goodType.toString());
        }
        //单价和货主控价
        if (goodsSourceDetail.getFreightType() != null) {
            if (goodsSourceDetail.getFreightType() == 1) {
                mBinding.itemGoodsOwnerFreight.setContent("电议");
                mBinding.itemGoodsFreight.setContent("电议");
            } else {
                mBinding.itemGoodsOwnerFreight.setContent(String.format("%s元", NumberUtil.trim0(goodsSourceDetail.getAllFreight())));
                mBinding.itemGoodsFreight.setContent(NumberUtil.trim0(goodsSourceDetail.getFreight()) + goodsSourceDetail.getFreightUnitType());
            }
        } else {
            mBinding.itemGoodsOwnerFreight.setContent(String.format("%s元", NumberUtil.trim0(goodsSourceDetail.getAllFreight())));
            mBinding.itemGoodsFreight.setContent(NumberUtil.trim0(goodsSourceDetail.getFreight()) + goodsSourceDetail.getFreightUnitType());
        }
        //运量
        if (TextUtils.isEmpty(goodsSourceDetail.getWeight())) {
            if (!TextUtils.isEmpty(goodsSourceDetail.getVolume())) {
                mBinding.itemGoodsWeight.setContent(NumberUtil.trim0(goodsSourceDetail.getVolume()) + "方");
            } else {
                mBinding.itemGoodsWeight.setContent("/");
            }
        } else {
            mBinding.itemGoodsWeight.setContent(NumberUtil.trim0(goodsSourceDetail.getWeight()) + "吨" + (TextUtils.isEmpty(goodsSourceDetail.getVolume()) ? "" : "/" + NumberUtil.trim0(goodsSourceDetail.getVolume()) + "方"));
        }
        //发票要求
        mBinding.itemGoodsFapiao.setContent(TextUtils.isEmpty(goodsSourceDetail.getInvoiceWords()) ? "/" : goodsSourceDetail.getInvoiceWords().equals("不开发票") ? goodsSourceDetail.getInvoiceWords() :
                NumberUtil.trim0(goodsSourceDetail.getTariff()) + "%" + goodsSourceDetail.getInvoiceWords());
        //联系信息
        mBinding.itemGoodsOwnerInfo.setContent(goodsSourceDetail.getConnection() + "/" + goodsSourceDetail.getConnectionPhone());
        //装车时间
        if (CargoConstant.stampFormatLoadInput(goodsSourceDetail.getShipmentTime(), goodsSourceDetail.getStartPointTime()).equals(CargoConstant.stampFormatLoadInput(goodsSourceDetail.getShipmentEndTime(), goodsSourceDetail.getEndPointTime()))) {
            mBinding.itemGoodsLoadTime.setContent(CargoConstant.stampFormatLoadInput(goodsSourceDetail.getShipmentTime(), goodsSourceDetail.getStartPointTime()));
        } else {
            mBinding.itemGoodsLoadTime.setContent(CargoConstant.stampFormatLoadInput(goodsSourceDetail.getShipmentTime(), goodsSourceDetail.getStartPointTime()) + (TextUtils.isEmpty(CargoConstant.stampFormatLoadInput(goodsSourceDetail.getShipmentEndTime(), goodsSourceDetail.getEndPointTime())) ? "" : "-") + CargoConstant.stampFormatLoadInput(goodsSourceDetail.getShipmentEndTime(), goodsSourceDetail.getEndPointTime()));
        }

        //装货时间
        long currentTime = DateUtils.getCustomizeDayMorning(0, System.currentTimeMillis()).getTime();
        long beginTime = goodsSourceDetail.getShipmentTime();
        //若当天日期在装货开始日期之后，则默认值为当天日期，否则，默认值为装货开始时间（日期）
        if (beginTime < currentTime) {
            mBinding.itemArriveTime.setContent(DateUtils.getDate());
            mEntity.setInTime(currentTime);
        } else {
            mBinding.itemArriveTime.setContent(DateUtils.timestampTo13DateNos(beginTime));
            mEntity.setInTime(beginTime);
        }
    }


    /**
     * 装载货源信息
     */
    private void loadGoodsSourceInfo(List<String> strings, WrapLinearLayout lay_gallery) {
        lay_gallery.removeAllViews();
        LayoutInflater mInflater = LayoutInflater.from(getActivity());
        if (strings != null && strings.size() != 0) {
            for (int i = 0; i < strings.size(); i++) {
                final View view = mInflater.inflate(R.layout.item_goods_transport_info_02, lay_gallery, false);
                final TextView tv_info = view.findViewById(R.id.tv_info);
                tv_info.setText(strings.get(i));
                lay_gallery.addView(view);
            }
        }
    }

    /**
     * 初始化车辆选择器
     */
    private void syncCarList(List<CarInfo> list, boolean isReFresh) {
        mCarList.clear();
        if (list == null) return;
        mCarList.addAll(list);

        carListPopWindow.setData(list);

        if (!isReFresh) {
            //当只有一辆车时，填入默认值
            if (mCarList.size() == 1) {
                carSelect(0);
            }
        } else {
            carSelect(pos);
        }
    }


    /**
     * 车辆选择
     */
    private void carSelect(int index) {
        car = mCarList.get(index);
        StringBuilder strBuilder = new StringBuilder();
        if (!TextUtils.isEmpty(car.getCarNumber())) {
            strBuilder.append(car.getCarNumber());
        }
        if (!TextUtils.isEmpty(car.getCarTypeName())) {
            strBuilder.append(" ");
            strBuilder.append(car.getCarTypeName());
        }
        if (!TextUtils.isEmpty(car.getCarLenName())) {
            strBuilder.append(" ");
            strBuilder.append("长" + car.getCarLenName());
        }
        if (BigDecimal.ZERO.compareTo(BigDecimal.valueOf(car.getWeight())) != 0) {
            strBuilder.append(" ");
            strBuilder.append(NumberUtil.trim0(car.getWeight()) + "吨");
        }
        if (!TextUtils.isEmpty(car.getHeightHurdle())) {
            strBuilder.append(" ");
            strBuilder.append("栏高" + car.getHeightHurdle() + "米");
        }
        if (car.getIsDump() != null) {
            strBuilder.append(" ");
            if (car.getIsDump() == 0) {
                strBuilder.append("非自卸");
            } else if (car.getIsDump() == 1) {
                strBuilder.append("自卸");
            }
        }
        mBinding.itemCarriageCar.setContent(strBuilder.toString());
        mEntity.setCarNo(car.getNo());
        mEntity.setCarNumber(car.getCarNumber());
        if (car.getIsComplete() == 1) {
            mEntity.setCarLenNo(car.getCarLenNo());
            mEntity.setCarTypeNo(car.getCarTypeNo());
        }
        mEntity.setDriverNo(car.getNo());

    }

    /**
     * 同步定位信息
     */
    private void syncLocation(AMapAddressEntity entity) {
        if (entity == null) return;
        mBinding.itemLocation.setContent(String.format("%s%s%s",
                entity.getProvince(),
                entity.getCity(),
                entity.getDistrict()));
        mEntity.setLat(entity.getLatitude());
        mEntity.setLng(entity.getLongitude());
        mEntity.setProvinceName(entity.getProvince());
        mEntity.setCityName(entity.getCity());
        mEntity.setDistrictName(entity.getDistrict());
        mEntity.setProvinceNo(entity.getProvinceNo());
        mEntity.setCityNo(entity.getCityNo());
        mEntity.setDistrictNo(entity.getDistrictNo());
        mEntity.setDetailAddress(entity.getSnippet());
        mBinding.etCargoOrdersAddress.setVisibility(View.VISIBLE);
        mBinding.etAddressLine.setVisibility(View.VISIBLE);
        mBinding.etCargoOrdersAddress.setText(DefaultUtil.getString(entity.getSnippet()));
        mEntity.setContrcts(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.REAL_NAME, ""));
        mEntity.setContrctsNumber(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_PHONE, ""));
        mEntity.setOfferType(3);
    }

    @Override
    public void onClick(View v) {
        if (v == mBinding.includeTitle.ivBack) {
            finish();
        } else if (v == mBinding.btnAllFreight) {//报总价
            mBinding.btnAllFreight.setChecked(true);
            mBinding.btnFreight.setChecked(false);
            //设置CheckBox对象的位置，对应为左、上、右、下
            mBinding.btnAllFreight.setCompoundDrawables(drawableSelect, null, null, null);
            mBinding.btnFreight.setCompoundDrawables(drawableUnSelect, null, null, null);
            mBinding.llFreightUnit.setVisibility(View.GONE);
            mBinding.viewLineFreightUnit.setVisibility(View.GONE);
            mBinding.tvReleaseCargoFreightSuffix.setText("元");
            mBinding.tvQuoteFreight.setHint("请输入运费");
        } else if (v == mBinding.btnFreight) {//报单价
            mBinding.btnAllFreight.setChecked(false);
            mBinding.btnFreight.setChecked(true);
            // 设置CheckBox对象的位置，对应为左、上、右、下
            mBinding.btnFreight.setCompoundDrawables(drawableSelect, null, null, null);
            mBinding.btnAllFreight.setCompoundDrawables(drawableUnSelect, null, null, null);
            mBinding.llFreightUnit.setVisibility(View.VISIBLE);
            mBinding.viewLineFreightUnit.setVisibility(View.VISIBLE);
            switchFreightMode(0);
            mBinding.tvQuoteFreight.setHint("请输入单价");

        } else if (v == mBinding.tvCargoOrdersAdd) {
            addField();
        } else if (v == mBinding.tvCargoOrdersSubmit) {
            clearAllFocus();
            String adress = mBinding.etCargoOrdersAddress.getText().toString();
            if (TextUtils.isEmpty(adress)) {
                new RoundDialog.Builder(this)
                        .title("提示")
                        .content("请输入楼牌号")
                        .cancel("暂不填写")
                        .singleBtn(true)
                        .contentGravity(Gravity.CENTER)
                        .show();
                return;
            }
            String carInfo = mBinding.itemCarriageCar.getContent();
            if (TextUtils.isEmpty(carInfo)) {
                new RoundDialog.Builder(this)
                        .title("提示")
                        .content("请选择车辆")
                        .cancel("暂不填写")
                        .singleBtn(true)
                        .contentGravity(Gravity.CENTER)
                        .show();
                return;
            }
            if (car != null && car.getIsComplete() == 0) {
                new RoundDialog.Builder(this)
                        .title("提示")
                        .content("请先完善" + car.getCarNumber() + "的车辆信息")
                        .cancel("暂不完善")
                        .confirm("确定").confirmCallback(view -> {
                    Intent intent = new Intent(this, AddCarInfoActivity.class);
                    intent.putExtra("carNo", Long.valueOf(car.getNo()));
                    startActivity(intent);
                }).show();
                return;
            }
            try {
                BigDecimal bg = new BigDecimal(NumberUtil.convertToDouble(mBinding.tvQuoteFreight.getText().toString()));
                double freight = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

                if (freight < 0.01 || freight > 9999999999.99) {
                    MToast.showToast(this, "请输入9999999999内的报价");
                    return;
                }
                if (mBinding.btnAllFreight.isChecked()) {
                    mEntity.setAllFreight(NumberUtil.trim0(freight));
                    mEntity.setFreight(null);
                    mEntity.setFreightUnit(0);
                } else {
                    if (mBinding.tvReleaseCargoOnce.isSelected()) {
                        mEntity.setFreight(NumberUtil.trim0(freight));
                        mEntity.setFreightUnit(CargoPublishEntity.FreightMode.MODE_ONCE);
                        mEntity.setAllFreight(null);
                    } else if (mBinding.tvReleaseCargoWeight.isSelected()) {
                        mEntity.setFreight(NumberUtil.trim0(freight));
                        mEntity.setFreightUnit(CargoPublishEntity.FreightMode.MODE_WEIGHT);
                        mEntity.setAllFreight(null);
                    } else if (mBinding.tvReleaseCargoVolume.isSelected()) {
                        mEntity.setFreight(NumberUtil.trim0(freight));
                        mEntity.setFreightUnit(CargoPublishEntity.FreightMode.MODE_VOLUME);
                        mEntity.setAllFreight(null);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (!mBinding.cbCargoOrdersProtocol.isChecked()) {
                MToast.showToast(this, "请先勾选运输协议");
                return;
            }
            toPayOrder();
        } else if (v == mBinding.tvCargoOrdersProtocol) {
            EventBus.getDefault().postSticky(WebEvent.make(EventConstant.EVENT_WEBVIEW, UrlConfig.NEW_BASE_URL + "logistics/operate/html/file/transportAgreement"));
            WebActivity.start(this);
        } else if (v == mBinding.tvReleaseCargoOnce) {
            if (mBinding.tvReleaseCargoOnce.isSelected()) {
                return;
            }
            switchFreightMode(0);
        } else if (v == mBinding.tvReleaseCargoWeight) {
            if (mBinding.tvReleaseCargoWeight.isSelected()) {
                return;
            }
            switchFreightMode(1);
        } else if (v == mBinding.tvReleaseCargoVolume) {
            if (mBinding.tvReleaseCargoVolume.isSelected()) {
                return;
            }
            switchFreightMode(2);
        }
    }

    /**
     * 切换运费方式
     */
    private void switchFreightMode(int position) {
        int count = mBinding.llReleaseCargoFreightType.getChildCount();
        for (int i = 0; i < count; i++) {
            mBinding.llReleaseCargoFreightType.getChildAt(i).setSelected(false);
        }
        mBinding.llReleaseCargoFreightType.getChildAt(position).setSelected(true);
        //设置运费方式
        switch (position) {
            case 0:
                mEntity.setFreightUnit(CargoPublishEntity.FreightMode.MODE_ONCE);
                mBinding.tvReleaseCargoFreightSuffix.setText("元/趟");
                break;
            case 1:
                mEntity.setFreightUnit(CargoPublishEntity.FreightMode.MODE_WEIGHT);
                mBinding.tvReleaseCargoFreightSuffix.setText("元/吨");
                break;
            case 2:
                mEntity.setFreightUnit(CargoPublishEntity.FreightMode.MODE_VOLUME);
                mBinding.tvReleaseCargoFreightSuffix.setText("元/方");
                break;
        }
    }

    @Override
    public void OnWholeItemClick(View v) {
        if (v == mBinding.itemArriveTime) {//预计到场时间
            setInsuranceTime();
        } else if (v == mBinding.itemLocation) {//所在地
            AMapDialog.launch(this);
        } else if (v == mBinding.itemCarriageCar) {//车辆信息
            if (carListPopWindow != null) {
                carListPopWindow.showDownPopwindow(mBinding.itemCarriageCar, true);
                carListPopWindow.backgroundAlpha(0.5f);
            }
        }
    }

    private void setInsuranceTime() {
        if (mEntity != null && mEntity.getInTime() != null) {
            Date time = new Date(mEntity.getInTime());
            selectedDate.setTime(time);
        }
        TimePickerView timePickerinsurance = new TimePickerBuilder(this, (date, v) -> {
//            if (date.getTime() > goodsSourceDetail.getShipmentEndTime()) {
//                RoundDialogHelper.showSingleDialog(getActivity(), "提示",
//                        "当前货源最后可装货时间为" + CargoConstant.stampFormatLoadInput(goodsSourceDetail.getShipmentEndTime(), goodsSourceDetail.getEndPointTime()) + "，请重新选择预计到场时间",
//                        "确定", true, com.sgb.trip.R.color.color_5792FD, new RoundDialogHelper.DialogFunction() {
//                            @Override
//                            public void normalRoundDialog() {
//
//                            }
//                        });
//                return;
//            }
            @SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
            String format = sdf.format(date);
            mBinding.itemArriveTime.setContent(format);
            mEntity.setInTime(date.getTime());
        }).setType(new boolean[]{true, true, true, false, false, false}).setCancelText("取消").setSubCalSize(15)
                .setRangDate(Calendar.getInstance(), null)
                .setCancelColor(Color.parseColor("#666666"))
                .setTitleColor(Color.parseColor("#969696")).setTitleSize(15)
                .setSubmitText("确定")
                .setSubmitColor(Color.parseColor("#5792FD"))
                .setTextColorCenter(Color.parseColor("#ff333333"))
                .setContentTextSize(15)
                .setLineSpacingMultiplier(2.5f)
                .setDividerColor(Color.parseColor("#EDEDED"))
                .setTitleText("预计到场时间")
                .build();
//        if (selectedDate != null) {
//            timePickerinsurance.setDate(selectedDate);
//        }
        timePickerinsurance.show();
    }

    public void toPayOrder() {
        mEntity.setDetailAddress(mBinding.etCargoOrdersAddress.getText().toString());
        if (mBinding.etCargoQuotationMark.getText() != null && !TextUtils.isEmpty(mBinding.etCargoQuotationMark.getText().toString())) {
            mEntity.setNote(mBinding.etCargoQuotationMark.getText().toString());//承运承诺传入备注字段
        }
        if (mBinding.etCargoSaleNotice.getText() != null && !TextUtils.isEmpty(mBinding.etCargoSaleNotice.getText().toString())) {
            mEntity.setMarketingPublicity(mBinding.etCargoSaleNotice.getText().toString());
        }
        //新增字段json
        if (mCustomList != null && mCustomList.size() > 0) {
            JsonObject field = new JsonObject();
            for (SingleItemEntity diy : mCustomList) {
                field.addProperty(diy.getLeftString(), diy.getRightString());
            }
            mEntity.setAddField(field.toString());
        }
        mEntity.setIsVoluntarily(3);

        mViewModel.realQuotation(this, mEntity);
    }

    /**
     * 添加更多字段
     */
    private void addField() {
        if (mCustomList.size() >= 3) {
            MToast.showToast(this, "最多添加3个字段");
            return;
        }
        mCustomList.add(new SingleItemEntity());
        mCustomAdapter.notifyDataSetChanged();
        if (mBinding.rvCargoOrdersField.getVisibility() == View.GONE) {
            mBinding.rvCargoOrdersField.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && resultCode == RESULT_CODE) {
            if (data != null && !TextUtils.isEmpty(data.getStringExtra("no"))) {
                Intent intent = new Intent();
                intent.putExtra("no", data.getStringExtra("no"));
                setResult(RESULT_CODE, intent);
            } else {
                setResult(RESULT_CODE);
            }
            finish();
        } else {
            AMapAddressEntity entity = AMapDialog.get(data);
            if (entity != null) {
                mBinding.itemLocation.setContent(String.format("%s%s%s",
                        entity.getProvince(),
                        entity.getCity(),
                        entity.getDistrict()));
                mBinding.etCargoOrdersAddress.setVisibility(View.VISIBLE);
                mBinding.etAddressLine.setVisibility(View.VISIBLE);
                mBinding.etCargoOrdersAddress.setText(DefaultUtil.getString(entity.getSnippet()));
                //设置数据
                mEntity.setLat(entity.getLatitude());
                mEntity.setLng(entity.getLongitude());
                mEntity.setProvinceName(entity.getProvince());
                mEntity.setCityName(entity.getCity());
                mEntity.setDistrictName(entity.getDistrict());
                mEntity.setProvinceNo(entity.getProvinceNo());
                mEntity.setCityNo(entity.getCityNo());
                mEntity.setDistrictNo(entity.getDistrictNo());
                mEntity.setDetailAddress(entity.getSnippet());
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MenuEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_ORDER_FINISH) {
            finish();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(LogisticsEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_CARINFO_COMMIT) {
            mCarList.get(pos).setIsComplete(1);
            car = mCarList.get(pos);
            mViewModel.getReFreshCarInfo(this);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

}
